package com.gxa.ssm251.service.impl;

import com.gxa.ssm251.exception.BusinessException;
import com.gxa.ssm251.mapper.CouponMapper;
import com.gxa.ssm251.pojo.Coupon;
import com.gxa.ssm251.service.CouponService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 舒空
 */

//@Transactional(rollbackFor = Throwable.class)//出现error回滚
@Service("couponService")
public class CouponServiceImpl implements CouponService {

    @Resource
    private CouponMapper couponMapper;




    @Override
//    @Transactional(propagation = Propagation.REQUIRED)//创建事务

    public Integer addCoupon(Coupon coupon) throws BusinessException {
        Coupon coupon1 = couponMapper.selectByName(coupon.getName());
        if (coupon1==null){
            return couponMapper.insert(coupon);
        }else {
            throw new BusinessException("优惠券已存在");
        }
    }

    @Override
    public List<Coupon> selectById(Integer id) {
        return couponMapper.selectById(id);
    }

    @Override
    public Integer selectCountAll() {
        return couponMapper.selectCountAll();
    }

    @Override
    public List<Coupon> selectAllByPage(Integer page, Integer size) {
        return couponMapper.selectAllByPage(page,size);
    }

    @Override
    public Coupon selectByName(String name) {
        return couponMapper.selectByName(name);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED/*,isolation = Isolation.READ_COMMITTED默认COMMITTED*/)//创建事务

    public Integer addCpScope(Integer id,List<String> list) {
        Integer integer = 0;
        for (String s : list) {
            integer+= couponMapper.insertScope(id,Integer.valueOf(s));
        }
        return integer;
    }

    @Override
    public Boolean updateInUse(Coupon coupon) {
        return couponMapper.updateInUse(coupon);
    }

    @Override
    public Integer updateScope(Integer id, List<String> list) {
        Integer integer = couponMapper.deleteScope(id);
        Integer integer1=0;
        if (integer>0){
            for (String s : list) {
                integer1 += couponMapper.insertScope(id, Integer.valueOf(s));
            }
        }else {
            System.out.println("删除失败");
        }
        return integer1;
    }

    @Override
    public Integer update(Coupon coupon) {
        return couponMapper.update(coupon);
    }
}
